package cn.edu.jxust.core.infrastructure.handler;

import cn.edu.jxust.common.response.Result;
import cn.edu.jxust.common.response.ResultUtils;
import cn.edu.jxust.common.response.enums.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * @author QiuKangming
 * @version 1.0
 * @description 全局异常处理
 * @since 2020/06/18 16:39
 */

@Slf4j
@SuppressWarnings("all")
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public Result handler(MethodArgumentTypeMismatchException e){

        log.error("全局异常捕获 ---> [MethodArgumentTypeMismatchException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);

    }

    @ExceptionHandler(value = AuthorizationException.class)
    public Result handler(AuthorizationException e){

        log.error("运行时异常[AuthorizationException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.VISITED_FORBID);

    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result handler(HttpMessageNotReadableException e){

        log.error("参数异常[HttpMessageNotReadableException]: {}", e.getMessage());
        return ResultUtils.resultWithoutData(ResultStatus.PARAM_ERROR);

    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){

        log.error("实体校验异常[RuntimeException]: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultUtils.resultWithoutData(ResultStatus.ENETITY_FAILED, objectError.getDefaultMessage());

    }

}
